package com.zytlifeservice.service;

import com.google.gson.Gson;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import com.zytlifeservice.constant.VerifyConstant;
import com.zytlifeservice.domain.Verify;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.VerifyRepository;
import com.zytlifeservice.response.VerifyResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by MJS on 2017/5/2.
 */
@Service
public class VerifyManager {

    private static final Logger logger = LoggerFactory.getLogger(VerifyManager.class);


    static String url = "http://gw.api.taobao.com/router/rest";
    //        String appkey = "23762732";
    static String appkey = "23811125";
    //        String secret = "30db573acaf49c020abaf2c3c9764c8a";
    static String secret = "c7d88d6826bc5f0e7c39c236c4a2a2ee";

    private static TaobaoClient taobaoClient = new DefaultTaobaoClient(url, appkey, secret);
    @Autowired
    VerifyRepository verifyRepository;

    @Transactional
    public void sendVerify(String mobile) {
        String number = getSixVerify();
        logger.info("生成的随机数={}", number);
        String url = "http://gw.api.taobao.com/router/rest";
//        String appkey = "23762732";
        String appkey = "23811125";
//        String secret = "30db573acaf49c020abaf2c3c9764c8a";
        String secret = "c7d88d6826bc5f0e7c39c236c4a2a2ee";
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("");
        req.setSmsType("normal");
//        req.setSmsFreeSignName("田骁");
        req.setSmsFreeSignName("爱客来");
        req.setSmsParamString(String.format("{number:'%s'}", number));
        req.setRecNum(mobile);
//        req.setSmsTemplateCode("SMS_62570174");
        req.setSmsTemplateCode("SMS_66605120");
        AlibabaAliqinFcSmsNumSendResponse rsp = null;
        try {
            rsp = taobaoClient.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
            throw new UserException("验证码发送失败", 104);
        }
        logger.info("base res={}", rsp.getBody());
        Gson gson = new Gson();
        VerifyResponse verifyResponse = gson.fromJson(rsp.getBody(), VerifyResponse.class);
        logger.info("json res={}", verifyResponse);
        if (verifyResponse == null) {
            throw new UserException("验证码发送失败", 103);
        }

        if (verifyResponse.getAlibaba_aliqin_fc_sms_num_send_response() != null) {
            if (verifyResponse.getAlibaba_aliqin_fc_sms_num_send_response().getResult().isSuccess()) {
                logger.info("remove verify count={}", verifyRepository.removeAllByMobile(mobile));
                Verify verify = new Verify();
                verify.setMobile(mobile);
                verify.setSendTime(new Date());
                verify.setStatus(VerifyConstant.STATUS_UN_ACTIVE);
                verify.setVerifyCode(number);
                verifyRepository.save(verify);
            } else {
                throw new UserException("验证码发送失败", 104);
            }
        } else if (verifyResponse.getError_response() != null) {
            if ("isv.BUSINESS_LIMIT_CONTROL".equals(verifyResponse.getError_response().getSub_code())) {
                throw new UserException("请求次数超过限制", 103);
            } else {
                throw new UserException(verifyResponse.getError_response().getSub_msg(), 104);
            }
        }
    }

    private String getSixVerify() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

}
